import { Injectable, Injector, Inject } from '@angular/core';
import { _HttpClient } from '@delon/theme';
import { SFSchemaEnumType } from '@delon/form';
import { Observable } from 'rxjs';
import { map } from 'rxjs/internal/operators/map';
import { environment } from '@env/environment';

@Injectable()
export class DictService {
  constructor(public http: _HttpClient, private injector: Injector) {}

  private _dicts: Map<string, any[]> = new Map();

  getTypeAll(): Observable<SFSchemaEnumType[]> {
    return this.http.get(`${environment.sys.ctx}/sysDict/findTypeAll`).pipe(
      map(items => {
        // tslint:disable-next-line: prefer-const
        let emunTypes: SFSchemaEnumType[] = [];

        items.forEach((element : any) => {
          emunTypes.push({
            label: element.typeName,
            value: element.type,
          });
        });
        return emunTypes;
      }),
    );
  }

  getSFSchemaEnumTypes(type: string): Observable<SFSchemaEnumType[]> {
    return this.http.get(`${environment.sys.ctx}/sysDict/findByType/${type}`).pipe(
      map(items => {
        // tslint:disable-next-line: prefer-const
        let emunTypes: SFSchemaEnumType[] = [];

        items.forEach((element : any) => {
          emunTypes.push({
            label: element.value,
            value: element.key,
          });
        });
        return emunTypes;
      }),
    );
  }

  async getSTColumnBT(type: string): Promise<any> {
    return this.http
      .get(`${environment.sys.ctx}/sysDict/findByType/${type}`)
      .pipe(
        map(items => {
          const badge: any = {};
          items.forEach((element : any) => {
            badge[element.key] = {
              text: element.value,
              color: 'default',
            };
          });
          return badge;
        }),
      )
      .toPromise();
  }

  async getMapByType(type: string): Promise<any> {
    const data: any = {};
    let dicts: any[] = [];

    if (this._dicts.has(type)) {
      dicts = this._dicts.get(type) as any;
    } else {
      dicts = await this.http.get(`${environment.sys.ctx}/sysDict/findByType/${type}`).toPromise();
    }

    dicts.forEach(dict => {
      data[dict.key] = dict.value;
    });

    return new Promise<string[]>(resolve => {
      resolve(data);
    });
  }
}
